<template>
  <el-container class='elheight'>
    <el-aside class="appTree">
      <app-tree v-bind:tree-data="allDictKeyData" :props="defaultProps" v-on:appTreeClick="treeClickHandle"></app-tree>
    </el-aside>
    <el-main>
      <el-container>
        <el-header class="dzy-main-header">
          <div class="btn-group-el">
            <btn-group :currentSelectedData="currentSelectedData" @btnClickCallback="btnClickCallback"></btn-group>
          </div>
          <el-dialog :title="dialogTitleKey" :visible.sync="dialogFormVisibleKey" :before-close="cancel">
            <el-form :model="formDataKey"
                     :disabled="showOnlyKey"
                     label-width="120px"
                     size="mini">
              <el-form-item label="字典目录名称">
                <el-input v-model="formDataKey.keyName" placeholder="请输入字典目录名称"></el-input>
              </el-form-item>
              <el-form-item label="字典目录编码值">
                <el-input v-model="formDataKey.keyCode" placeholder="请输入字典目录编码值"></el-input>
              </el-form-item>
            </el-form>
            <div v-if="!showOnlyKey" slot="footer" class="dialog-footer">
              <el-button @click="cancel">取 消</el-button>
              <el-button type="primary" @click="saveKey">提 交</el-button>
            </div>
          </el-dialog>
          <div class="dzy-custom-search-box">
            <div>字典值名称：<el-input placeholder="请输入字典值名称" v-model="queryData.name" clearable class="dzy-custom-input"></el-input></div>
            <div>字典名称：<el-input placeholder="请输入字典名称" v-model="queryData.keyName"  clearable class="dzy-custom-input"></el-input></div>
            <div><el-button @click="searchHandleClick" type="primary" icon="el-icon-search">查询</el-button></div>
            <div class="createV"><el-button @click="clearQueryData" type="primary" icon="el-icon-search">查询所有</el-button></div>
            <div class="createV"><el-button @click="createValue" type="primary" icon="el-icon-plus">新增字典值</el-button></div>
          </div>
        </el-header>
        <el-main>
          <app-table
            :page-data="pageData"
            :table-columns="tableColumns"
            v-on:currentChange="handleCurrentChange"
            v-on:handleCheckedRows="handleCheckedRows"
            v-on:checkSingleRow="checkSingleRow"
            v-on:changeSingleRow="changeSingleRow"
            v-on:deleSingleRow="deleSingleRow" />
          <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :before-close="cancelValue">
            <el-form :model="formData"
                     :disabled="showOnly"
                     :rules="rules"
                     ref="formData"
                     label-width="120px"
                     size="mini">
              <el-form-item label="字典名称" prop="keyId">
                <cascader-tree
                  v-model="formData.keyId"
                  :tree-data="treeData"
                  :is-obj-data-return="true"
                  v-on:bindRegionAllMode="bindRegionAllMode"
                  placeholder="请选择字典名称"></cascader-tree>
              </el-form-item>
              <el-form-item label="上级字典值名称" prop="valuePId">
                <cascader-tree
                  v-model="formData.valuePId"
                  :tree-data="treeDataHierarchy"
                  :is-obj-data-return="true"
                  v-on:bindRegionAllMode="getDickValueHierarchy"
                  placeholder="请选择上级字典值名称"></cascader-tree>
              </el-form-item>
              <el-form-item label="字典值名称" prop="name">
                <el-input  v-model="formData.name" placeholder="请输入字典值名称"></el-input>
              </el-form-item>
              <el-form-item label="字典值编号" prop="code">
                <el-input  v-model="formData.code" placeholder="请输入字典值编号"></el-input>
              </el-form-item>
            </el-form>
            <div v-if="!showOnly" slot="footer" class="dialog-footer">
              <el-button @click="cancelValue('formData')">取 消</el-button>
              <el-button type="primary" @click="save('formData')" >提 交</el-button>
            </div>
          </el-dialog>
        </el-main>
      </el-container>
    </el-main>
  </el-container>
</template>

<script>
import BtnGroup from '@/components/BtnGroup'
import AppTable from '@/components/AppTable'
import AppTree from '@/components/common/AppTree'
import {isCommonDo} from '@/utils/CommonUtil'
import CascaderTree from '@/components/CascaderTree'
import {findDictionaryValue, creatDictionaryValue, updateDictionaryValue, delDictionaryValue, listDictionaryKey, createTreeNode, delTreeNode, updateTreeNode, listTreeNode, listDictionaryValueHierarchy} from '@/http/AppApi'
export default {
  data () {
    return {
      tableData: [],
      treeData: [],
      treeDataHierarchy: [],
      pageData: {},
      formData: {
        keyId: '',
        valuePId: '',
        name: '',
        code: ''
      },
      formDataKey: {},
      queryData: {},
      allDictKeyData: [],
      dialogTitle: '',
      dialogTitleKey: '新增字典',
      dialogFormVisible: false,
      dialogFormVisibleKey: false,
      currentSelectedData: [],
      showOnly: false,
      showOnlyKey: false,
      delId: '',
      createParam: {},
      tableColumns: [
        { label: '字典值编号', prop: 'code' },
        { label: '字典值名称', prop: 'name' },
        { label: '字典编号', prop: 'keyCode' },
        { label: '字典名称', prop: 'keyName' }
      ],
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      rules: {
        keyId: [{
          required: true,
          message: '请选择字典编码',
          trigger: 'change'
        }],
        // valuePId: [{
        //   required: true,
        //   message: '请输入字典值编码层级',
        //   trigger: 'change'
        // }],
        name: [{
          required: true,
          message: '请输入字典值名称',
          trigger: 'change'
        }],
        code: [{
          required: true,
          message: '请输入字典值编号',
          trigger: 'change'
        }]
      }
    }
  },
  components: {
    BtnGroup,
    AppTree,
    AppTable,
    CascaderTree
  },
  mounted () {
    this.getTableData()
    this.getAllDictKeyData()
    // this.getDickValueHierarchy()
  },
  methods: {
    bindRegionAllMode (data) {
      this.formData.keyId = data.id
      // this.formData.keyName = data.name
      // this.formData.keyCode = data.code
      let param = {}
      param.keyId = data.id
      listDictionaryValueHierarchy(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.treeDataHierarchy = resp.data
          // let treeData = []
          // treeData.push({name: '顶级', id: '0', children: resp.data})
          // this.treeDataHierarchy = treeData
        }
      })
    },
    getDickValueHierarchy (data) {
      this.formData.valuePId = data.id
    },
    save (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          if (this.formData) {
            if (this.formData.id) {
              let object = {}
              object = this.formData
              updateDictionaryValue(object).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.cancel()
                  this.$message({
                    showClose: true,
                    message: '修改成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: resp.message
                  })
                }
              })
            } else {
              creatDictionaryValue(this.formData).then(resp => {
                if (resp.code && resp.code === '200') {
                  this.getTableData()
                  this.cancelValue()
                  // this.$refs[formName].clearValidate()
                  this.$refs[formName].resetFields()
                  // this.formData.keyId = ''
                  this.$message({
                    showClose: true,
                    message: '新增成功',
                    type: 'success'
                  })
                } else {
                  this.$message({
                    type: 'info',
                    message: resp.message
                  })
                }
              })
            }
          }
        } else {
          return false
        }
      })
    },
    saveKey () {
      if (this.formDataKey) {
        if (this.formDataKey.id) {
          let object = {}
          object = this.formDataKey
          updateTreeNode(object).then(resp => {
            if (resp.code && resp.code === '200') {
              this.cancel()
              this.getAllDictKeyData()
              this.$message({
                showClose: true,
                message: '修改成功',
                type: 'success'
              })
            } else {
              this.$message({
                type: 'info',
                message: resp.message
              })
            }
          })
        } else {
          createTreeNode(this.formDataKey).then(resp => {
            if (resp.code && resp.code === '200') {
              this.cancel()
              this.getAllDictKeyData()
              this.$message({
                showClose: true,
                message: '新增成功',
                type: 'success'
              })
            } else {
              this.$message({
                type: 'info',
                message: resp.message
              })
            }
          })
        }
      }
    },
    del (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.$confirm('此操作将永久删除, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          rows.forEach(row => {
            delDictionaryValue(row).then(resp => {
              if (resp.code && resp.code === '200') {
                this.getTableData()
                this.$message({
                  showClose: true,
                  message: '删除成功',
                  type: 'success'
                })
              } else {
                this.$message({
                  type: 'info',
                  message: resp.message
                })
              }
            })
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      }
    },
    delTreeNode () {
      if (this.delId === '') {
        this.$message({
          type: 'info',
          message: '请选中节点'
        })
      } else {
        let object = {}
        object.id = this.delId
        delTreeNode(object).then(resp => {
          if (resp.code && resp.code === '200') {
            this.getAllDictKeyData()
            this.delId = ''
            this.$message({
              showClose: true,
              message: '删除成功',
              type: 'success'
            })
          } else {
            this.$message({
              type: 'info',
              message: resp.message
            })
          }
        })
      }
    },
    updateTreeND () {
      if (this.delId === '') {
        this.$message({
          type: 'info',
          message: '请选中节点'
        })
      } else {
        let object = {}
        object.id = this.delId
        listTreeNode(object).then(resp => {
          if (resp.code && resp.code === '200') {
            let data = resp.data
            if (data) {
              this.formDataKey = data
              this.formDataKey.id = this.delId
            }
          } else {
            this.$message({
              type: 'info',
              message: resp.message
            })
          }
        })
        this.dialogFormVisibleKey = true
      }
    },
    cancel () {
      this.dialogFormVisibleKey = false
      this.formDataKey = {}
    },
    cancelValue (formName) {
      this.dialogFormVisible = false
      // this.$nextTick(() => {
      //   this.$refs['ruleForm'].resetFields()
      // })
      if (this.$refs[formName] !== undefined) {
        this.$refs[formName].resetFields()
      }
    },
    getTableData () {
      let param = this.queryData
      findDictionaryValue(param).then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data) {
            this.pageData = data
            isCommonDo(this.pageData, this)
            if (this.pageData.items && this.pageData.items instanceof Array) {
              this.tableData = this.pageData.items
            }
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
        }
      })
    },
    checkSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    changeSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    deleSingleRow: function (callbackData) {
      this.btnClickCallback(callbackData)
    },
    createValue: function (callbackDataCreate) {
      let callbackData = {}
      callbackData.btnType = 'create'
      callbackData.id = this.createParam.id
      this.btnClickCallback(callbackData)
    },
    handleCurrentChange (val) {
      this.queryData.offset = (val - 1) * 10
      this.getTableData()
    },
    getAllDictKeyData () {
      listDictionaryKey().then(resp => {
        if (resp.code && resp.code === '200') {
          let data = resp.data
          if (data && data instanceof Array) {
            // this.allDictKeyData = data
            // this.treeData = data
            let dataTree = []
            dataTree.push({name: '字典名称', id: '000', children: data})
            this.allDictKeyData = dataTree
            this.treeData = data
          }
        } else {
          this.$message({
            type: 'info',
            message: resp.message
          })
        }
      })
    },
    btnClickCallback (callbackData) {
      if (callbackData.btnType === 'delete') {
        this.dialogFormVisible = false
        let rows = callbackData.rows
        this.del(rows)
      } else if (callbackData.btnType === 'create') {
        this.showOnly = false
        this.dialogTitle = '新增字典值'
        this.dialogFormVisible = true
        this.formData.keyId = callbackData.id
      } else {
        if (callbackData.btnType === 'post') {
          this.formData = {}
        } else {
          this.formData = callbackData.rows[0]
        }
        this.showOnly = callbackData.btnType === 'get'
        this.dialogTitle = callbackData.dialogTitle
        this.dialogFormVisible = true
      }
    },
    handleCheckedRows (rows) {
      if (rows && rows instanceof Array && rows.length > 0) {
        this.currentSelectedData = rows
        this.formData = rows[0]
      } else {
        this.currentSelectedData = []
        this.formData = []
      }
    },
    treeClickHandle (data) {
      this.queryData = {}
      // this.queryData.keyName = data.name
      this.queryData.id = data.id
      this.createParam.id = data.id
      this.getTableData()
      this.delId = data.id
      // 请求字典值编码层级数据
      let param = {}
      param.keyId = data.id
      listDictionaryValueHierarchy(param).then(resp => {
        if (resp.code && resp.code === '200') {
          this.treeDataHierarchy = resp.data
          // let treeData = []
          // treeData.push({name: '顶级', id: '0', children: resp.data})
          // this.treeDataHierarchy = treeData
        }
      })
    },
    createTreeNode () {
      this.formDataKey = {}
      this.dialogFormVisibleKey = true
      this.showOnlyKey = false
    },
    searchHandleClick () {
      this.queryData.offset = 0
      this.getTableData()
    },
    clearQueryData () {
      this.queryData = {}
      this.getTableData()
    }
  },
  computed: {},
  watch: {}
}
</script>
<style>
  .createV{
    margin-left: 1%;
  }
  .btn-group-el{
    padding: 0px 10px 4px;
  }
</style>
